import AvatarView from '@/pages/account/components/AvatarView';
import { updateMyUserUsingPost, userLogoutUsingPost } from '@/services/backend/userController';
import { ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { message } from 'antd';
import React from 'react';

import { history } from '@@/core/history';
import { flushSync } from 'react-dom';
import useStyles from './index.style';

const UserInfo: React.FC = () => {
  const { styles } = useStyles();

  const { initialState, setInitialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;

  const handleFinish = async (value: API.UserUpdateMyRequest) => {
    try {
      const res = await updateMyUserUsingPost({
        avatar: currentUser?.avatar,
        ...value,
      });
      if (res.code === 0) {
        message.success('更新基本信息成功');
        //退出登录
        flushSync(() => {
          setInitialState((s) => ({ ...s, currentUser: undefined }));
        });
        await userLogoutUsingPost();
        history.push('/user/login');
        return;
      }
    } catch (error: any) {
      message.error(error.message);
    }
  };
  return (
    <div className={styles.baseView}>
      <>
        <div className={styles.left}>
          <ProForm
            layout="vertical"
            onFinish={handleFinish}
            submitter={{
              searchConfig: {
                submitText: '更新基本信息',
              },
              render: (_, dom) => dom[1],
            }}
            initialValues={{
              ...currentUser,
            }}
          >
            <ProFormText
              width="md"
              name="username"
              label="用户名"
              rules={[
                {
                  required: true,
                  message: '请输入您的用户名!',
                },
              ]}
            />
            <ProFormTextArea
              name="profile"
              label="个人简介"
              rules={[
                {
                  required: true,
                  message: '请输入个人简介!',
                },
              ]}
              placeholder="个人简介"
            />
          </ProForm>
        </div>
        <div className={styles.right}>
          <AvatarView
            avatar={
              currentUser?.avatar ??
              'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png'
            }
          />
        </div>
      </>
    </div>
  );
};
export default UserInfo;
